package com.yuxinmuyu.sports_management.service.impl;

import com.alibaba.excel.EasyExcel;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuxinmuyu.sports_management.bean.dto.ExportSportsProjectDTO;
import com.yuxinmuyu.sports_management.bean.dto.FileDto;
import com.yuxinmuyu.sports_management.bean.entiy.SportsProject;
import com.yuxinmuyu.sports_management.bean.request.*;
import com.yuxinmuyu.sports_management.bean.response.*;
import com.yuxinmuyu.sports_management.exception.BusinessException;
import com.yuxinmuyu.sports_management.mapper.SportsProjectMapper;
import com.yuxinmuyu.sports_management.service.SportsProjectService;
import com.yuxinmuyu.sports_management.utils.UserUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SportsProjectServiceImpl implements SportsProjectService {
    @Resource
    SportsProjectMapper sportsProjectMapper;

    @Override
    public Page<SportsProject> getPage(GetSportsProjectRequest request) {
        Page<SportsProject>page=new Page<>(request.getCurrentPage(),request.getPageSize());
        page= sportsProjectMapper.getPage(page,request.getYearTermID(),request.getSportsName());
        return page;
    }

    @Override
    public List<YearTermResponse> getSelectList() {
        return sportsProjectMapper.getSelectList();
    }

    @Override
    public GetSportsInfoResponse getInfoByID(GetSportsInfoRequest request) {
        SportsProject sportsProject=sportsProjectMapper.selectById(request.getSportsID());
        GetSportsInfoResponse response=new GetSportsInfoResponse();
        if(Objects.isNull(sportsProject)){
            throw new BusinessException("不存在该信息！");
        }
        response.setSportsName(sportsProject.getSportsName());
        response.setSportsID(sportsProject.getSportsID());
        response.setYearTermID(sportsProject.getYearTermID());
        response.setSportsName(sportsProject.getSportsName());
        response.setSportsMemo(sportsProject.getSportsMemo());
        List<FileDto>list=new ArrayList<>();
        if(Objects.isNull(sportsProject.getFileUrl())||Objects.equals("",sportsProject.getFileUrl())){
            return response;
        }
        list.add(0,new FileDto(sportsProject.getFileName(),sportsProject.getFileUrl()));
        response.setFileList(list);
        return response;
    }

    /**
     * 自动开启事物，出现异常自动回滚
     * @param request
     */
    @Transactional( rollbackFor = Exception.class)
    @Override
    public void deleteInfoByID(GetSportsInfoRequest request) {
        int n=sportsProjectMapper.deleteById(request.getSportsID());
        if(n==0){
            throw new BusinessException("删除ID为"+request.getSportsID()+"的项目信息失败!");
        }
    }

    @Transactional( rollbackFor = Exception.class)
    @Override
    public void updateByID(UpdateSportsInfoRequest request) {
        int n=sportsProjectMapper.update(null,Wrappers.<SportsProject>lambdaUpdate().eq(
                SportsProject::getSportsID,request.getSportsID())
                .set(SportsProject::getSportsName,request.getSportsName())
                .set(SportsProject::getYearTermID,request.getYearTermID())
                .set(SportsProject::getSportsMemo,request.getSportsMemo())
                .set(SportsProject::getFileUrl,request.getFileUrl())
                .set(SportsProject::getLastDate,new Date())
                .set(SportsProject::getOperator, UserUtil.getUserName())
                .set(SportsProject::getFileName,request.getFileName())
        );
        if(n==0){
            throw new BusinessException("修改ID为"+request.getSportsID()+"的项目信息失败!");
        }
    }

    @Override
    public List<DeptResponse> getDept() {
        return sportsProjectMapper.getDept();
    }

    @Override
    public List<MajorResponse> getMajor(GetDeptNameRequest request) {
       return sportsProjectMapper.getMajor(request.getDeptID());
    }

    @Override
    public List<ClassResponse> getSClass(GetClassListRequest request) {
        return sportsProjectMapper.getSClass(request.getMajorID());
    }

    @Override
    public void export(GetSportsProjectRequest request, HttpServletResponse response) {
        Page<SportsProject>page=new Page<>(1,-1);
        page= sportsProjectMapper.getPage(page,request.getYearTermID(),request.getSportsName());
        try {
            List<SportsProject>list=page.getRecords();
            if(list.isEmpty()){
                throw new BusinessException("不存在数据！");
            }
            List<ExportSportsProjectDTO>exportList=new ArrayList<>();
            list.forEach(n->{
                ExportSportsProjectDTO dto=new ExportSportsProjectDTO();
                BeanUtil.copyProperties(n,dto);
                if(n.getType()==1){
                    dto.setTypeName("单人项目");
                }else{
                    dto.setTypeName("团队项目");
                }
                exportList.add(dto);
            });
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
            String currentTime = sdf.format(new Date());
            String originalFileName = "运动会项目名单";
            String fileName = URLEncoder.encode(originalFileName + "_" + currentTime, "UTF-8").replaceAll("\\+", "%20");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ExportSportsProjectDTO.class).sheet("1").doWrite(exportList);
        }catch (IOException e){
            throw new BusinessException("导出失败！");
        }
    }

}
